package cs236369.hw5;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Servlet implementation class AddTask
 */
@WebServlet({"/AddTask", "/AddTask/*"})
public class AddTask extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();
		PrintWriter out;
		try {
			out = response.getWriter();
		} catch (IOException e) {
			response.setStatus(400);
			return;
		}
		if(validateUserInput(request)) {
			// if no session- redirect to welcome page
			if(session == null || session.getAttribute("userName") == null) {
				response.sendRedirect(request.getContextPath() + InitListener.welcomePage);
				return;
			}			
			
			try {
				// create skills array
				ArrayList<Skill> skills = new ArrayList<Skill>();	// to add skills dynamically
				Skill[] sa = new Skill[0];	// a dummy array for creating skills arrays

				Map<String, String[]> params = request.getParameterMap();
				for (String parameter : params.keySet()) {
				    if(parameter.contains("newSkillId")) {
				    	try {
					    	int skillID = Integer.parseInt(params.get(parameter)[0]);
					    	if(skillID > -1 ) { skills.add(new Skill(skillID,"",true)); }
				    	} catch (NumberFormatException e) {
				    		throw new RescueMeException("illegal parameter", "Skill ID is incorrect");
						} 
				    }
				}
				
				String capacityString = request.getParameter("capacity");
				int capacity;
				try {
					if(capacityString == null || Integer.parseInt(capacityString) < 0) {
						capacity = -1;
					} else {
						capacity = Integer.parseInt(capacityString);
					}
				} catch (NumberFormatException e) {
					throw new RescueMeException("illegal parameter", "Capacity is not a positive integer");
				}
				double latPos, lonPos;
				try {
					latPos = Double.parseDouble(request.getParameter("latPos"));
					lonPos = Double.parseDouble(request.getParameter("lngPos"));
				} catch (NumberFormatException e) {
					throw new RescueMeException("illegal parameter", "Longitude or latitude parameters are incorrect");
				}
				Mission m = new Mission(-1, session.getAttribute("userName").toString(), null,
						request.getParameter("taskname"), capacity, request.getParameter("content"),
						latPos, lonPos, skills.toArray(sa));
				int taskID = DBConnection.addMission(m);
				response.setStatus(200);
				out.print(taskID);
			} catch (RescueMeException e) {
				response.setStatus(400);
				out.print(e.getMessage());
			}
		}
		else {
			response.setStatus(400);
			System.err.println("Invalid input parameters");
			out.print("Invalid input parameters");
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
	
	private boolean validateUserInput(HttpServletRequest request) {
		try {
			String capacityStr = request.getParameter("capacity");
			if(capacityStr != null && !capacityStr.isEmpty()) { 
				int capacity = Integer.parseInt(capacityStr);
				if(capacity < 0) { return false; }
			}
		} catch (NumberFormatException e) { return false; }
		return true;		
	}

}
